package com.dc.wifi.main.utils;

import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.util.Log;

import com.blankj.utilcode.util.LogUtils;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Stm32CommunicationTool {

    private static final String TAG = "Stm32CommunicationTool";
    private UsbManager usbManager;
    private UsbDevice device;
    private UsbDeviceConnection connection;
    private UsbInterface interfaceData;
    private UsbEndpoint inEndpoint;
    private UsbEndpoint outEndpoint;
    private ExecutorService executor;

    public Stm32CommunicationTool(UsbManager usbManager, UsbDevice device) {
        this.usbManager = usbManager;
        this.device = device;
        this.executor = Executors.newSingleThreadExecutor();
    }

    public boolean initialize() {
        connection = usbManager.openDevice(device);
        if (connection == null) {
            Log.e(TAG, "Failed to open device");
            return false;
        }

        // 假设设备配置和接口索引已知
        int interfaceIndex = 0;
        interfaceData = device.getInterface(0);
        if (!connection.claimInterface(interfaceData, true)) {
            Log.e(TAG, "Failed to claim interface");
            return false;
        }

        // 获取IN和OUT端点
        int endpointIndex = 0;
        outEndpoint = interfaceData.getEndpoint(endpointIndex);
        inEndpoint = interfaceData.getEndpoint(endpointIndex + 1);

        return true;
    }

    public void sendMessage(byte[] message) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    int bytesWritten = connection.bulkTransfer(outEndpoint, message, message.length, 0);
                    Log.d(TAG, "Bytes written: " + bytesWritten);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void receiveMessage(final MessageReceivedListener listener) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                byte[] buffer = new byte[64]; // 根据需要调整缓冲区大小
                while (!Thread.currentThread().isInterrupted()) {
                    try {
                        int bytesReceived = connection.bulkTransfer(inEndpoint, buffer, buffer.length, 0);
                        if (bytesReceived > 0 && listener != null) {
                            listener.onMessageReceived(buffer, bytesReceived);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }



    public void releaseResources() {
        if (connection != null) {
            connection.releaseInterface(interfaceData);
            connection.close();
        }
        executor.shutdown();
    }

    public interface MessageReceivedListener {
        void onMessageReceived(byte[] buffer, int length);
    }
}